package com.dinghui.mybatis.config;

import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

/**
 * @description 全局异常捕获
 */
@RestControllerAdvice
public class GlobalException {

    public static final String DEFAULT_ERROR_CODE = "1000000";

    public static final String DEFAULT_PARAM_ERROR_CODE = "1000001";

    private static final String DEFAULT_ERROR_MSG = "系统升级中,请稍后再试";

    private static final String DEFAULT_404_ERROR_MSG = "资源不存在";

    private static final String DEFAULT_PARAM_ERROR_MSG = "参数不合法";

    private static String getErrorMsg(List<ObjectError> objectErrors) {
        StringBuilder msgBuilder = new StringBuilder();
        for (ObjectError objectError : objectErrors) {
            msgBuilder.append(objectError.getDefaultMessage()).append(",");
        }
        String errorMessage = msgBuilder.toString();
        if (errorMessage.length() > 1) {
            errorMessage = errorMessage.substring(0, errorMessage.length() - 1);
        }
        return errorMessage;
    }

    /**
     * 全局异常捕捉处理
     *
     * @param ex 异常信息
     * @return 返回异常结果
     */
    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(Exception ex) {
        ex.printStackTrace();
        if (ex instanceof NoHandlerFoundException) {
            return Result.error(new CodeMsg(DEFAULT_ERROR_CODE, DEFAULT_404_ERROR_MSG));
        } else {
            return Result.error(new CodeMsg(DEFAULT_ERROR_CODE, DEFAULT_ERROR_MSG));
        }
    }

    @ExceptionHandler(value = BizException.class)
    public Result bizErrorHandler(BizException ex) {
        ex.printStackTrace();
        return Result.error(new CodeMsg(ex.getErrorCode(), ex.getErrorMsg()));
    }

//    @ExceptionHandler(value = InvalidateParamException.class)
//    public Result paramErrorHandler(InvalidateParamException ex) {
//        ex.printStackTrace();
//        return Result.error(DEFAULT_PARAM_ERROR_CODE, ex.getMsg());
//    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Result illegalArgumentException(IllegalArgumentException ex) {
        ex.printStackTrace();
        return Result.error(new CodeMsg(DEFAULT_PARAM_ERROR_CODE, DEFAULT_PARAM_ERROR_MSG));
    }

    @ExceptionHandler({ConstraintViolationException.class})
    public Result constraintViolationException(ConstraintViolationException ex) {
        ex.printStackTrace();
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        if (!CollectionUtils.isEmpty(constraintViolations)) {
            StringBuilder msgBuilder = new StringBuilder();
            for (ConstraintViolation constraintViolation : constraintViolations) {
                msgBuilder.append(constraintViolation.getMessage()).append(",");
            }
            String errorMessage = msgBuilder.toString();
            if (errorMessage.length() > 1) {
                errorMessage = errorMessage.substring(0, errorMessage.length() - 1);
            }
            return Result.error(new CodeMsg(DEFAULT_PARAM_ERROR_CODE, errorMessage));
        }
        return new Result(new CodeMsg(DEFAULT_ERROR_CODE, DEFAULT_ERROR_MSG));
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        ex.printStackTrace();
        List<ObjectError> objectErrors = ex.getBindingResult().getAllErrors();
        if (!CollectionUtils.isEmpty(objectErrors)) {
            return Result.error(new CodeMsg(DEFAULT_PARAM_ERROR_CODE, getErrorMsg(objectErrors)));
        }
        return new Result(new CodeMsg(DEFAULT_ERROR_CODE, DEFAULT_ERROR_MSG));
    }

    @ExceptionHandler({BindException.class})
    public Result bindException(BindException ex) {
        ex.printStackTrace();
        List<ObjectError> objectErrors = ex.getBindingResult().getAllErrors();
        if (!CollectionUtils.isEmpty(objectErrors)) {
            return Result.error(new CodeMsg(DEFAULT_PARAM_ERROR_CODE, getErrorMsg(objectErrors)));
        }
        return new Result(new CodeMsg(DEFAULT_ERROR_CODE, DEFAULT_ERROR_MSG));
    }
}
